import { isAliPay, isWeChat } from "./const-ua";
import * as alipaySDK from "./alipay";
import * as wxSDK from "./weixin";

/**
 * @func jsdk 初始化
 * @param {Function} callback
 * @param {Object} params npm 搭配weixin-js-sdk 引入 需要传递jWeixin即weixin-js-sdk对象
 */
function ready(callback, platformObject) {
  if (isAliPay) {
    if (platformObject) {
      // npm 形式引入miniSDK
      window.NUOMY = platformObject;
      return alipaySDK;
    } else {
      // 在html直接引入miniJSDK 运行
      if (window.my) {
        window.NUOMY = window.my;
        callback && callback(alipaySDK);
      } else {
        console.warn("正在加载支付宝:https://appx/web-view.min.js");
        // TODO:支付宝需要加载两JSDK,
        loadScript("https://appx/web-view.min.js", () => {
          window.NUOMY = window.my;
          callback && callback(alipaySDK);
        });
      }
    }
  }

  if (isWeChat) {
    if (platformObject) {
      window.NUOWX = platformObject;
      return wxSDK;
    } else {
      if (!window.WeixinJSBridge || !WeixinJSBridge.invoke) {
        const wxInit = () => {
          window.NUOWX = window.wx;
          if (!window.WeixinJSBridge || !WeixinJSBridge.invoke) {
            document.addEventListener(
              "WeixinJSBridgeReady",
              () => {
                callback(wxSDK);
              },
              false
            );
          } else {
            callback(wxSDK);
          }
        };
        if (!window.wx) {
          loadScript("https://res2.wx.qq.com/open/js/jweixin-1.6.0.js", () => {
            wxInit();
          });
        } else {
          wxInit();
        }
      } else {
        callback(wxSDK);
      }
    }
  }
}

/**
 * @func 动态加载js
 * @param {String} url js url地址
 * @param {Function} cb js加载成功回调
 */
function loadScript(url, cb) {
  const script = document.createElement("script");
  script.setAttribute("type", "text/javascript");
  script.setAttribute("src", url);

  script.onload = script.onreadystatechange = function () {
    if (
      !this.readyState ||
      this.readyState == "loaded" ||
      this.readyState == "complete"
    ) {
      cb && cb();
    }
    script.onload = script.onreadystatechange = null;
  };

  document.querySelector("head").appendChild(script);
}
export default ready;
